package io.gitee.thinkbungee.utils;

import cn.hutool.core.collection.CollectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 集合一些工具类
 *
 * @author chenyichang
 * @date 2022/3/1
 */
public class CollectionUtils {

    private static final Logger log = LoggerFactory.getLogger(CollectionUtils.class);

    /**
     * 复制集合
     *
     * @param sourceList  目标list
     * @param targetClass 要复制的类型
     * @param <T>         要复制的类型
     * @return
     */
    public static <T> List<T> copyList(List<?> sourceList, Class<T> targetClass) {
        if (CollectionUtil.isEmpty(sourceList)) {
            return new ArrayList<>();
        }
        List<T> targetList = new ArrayList<>();
        try {

            for (Object source : sourceList) {
                T target = targetClass.getDeclaredConstructor().newInstance();
                BeanUtils.copyProperties(source, target);
                targetList.add(target);
            }
        } catch (Exception e) {
            log.error("复制集合出现异常", e);
        }
        return targetList;
    }
}
